
package com.bobo.mall.search.service.impl;

import com.alibaba.fastjson.JSON;
import com.bobo.common.to.es.SkuEsModel;
import com.bobo.mall.search.config.MallElasticSearchConfig;
import com.bobo.mall.search.constant.ESConstant;
import com.bobo.mall.search.service.ElasticSaveService;
import lombok.extern.slf4j.Slf4j;
import org.elasticsearch.action.bulk.BulkRequest;
import org.elasticsearch.action.bulk.BulkResponse;
import org.elasticsearch.action.index.IndexRequest;
import org.elasticsearch.client.RestHighLevelClient;
import org.elasticsearch.common.xcontent.XContentType;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.io.IOException;
import java.util.Arrays;
import java.util.List;
import java.util.stream.Collectors;

/**
 * 商品上架功能
 */
@Service
@Slf4j
public class ElasticSaveSeriviceImpl implements ElasticSaveService {

    @Autowired
    private RestHighLevelClient restHighLevelClient;
    @Override
    public boolean productStatusUp(List<SkuEsModel> skuEsModels) throws IOException {

        // 保存到es
        // 1、给 es 建立好索引。product ，建立好映射
        // 2、给 es 保存数据
        // BulkRequest bulkRequest, RequestOptions options
        BulkRequest bulkRequest = new BulkRequest();
        for (SkuEsModel esModel : skuEsModels) {
            // 1、构造保存请求
            IndexRequest request = new IndexRequest(ESConstant.PRODUCT_INDEX);
            request.id(esModel.getSkuId().toString());
            String s = JSON.toJSONString(esModel);
            request.source(s, XContentType.JSON);
            bulkRequest.add(request);
        }
        BulkResponse response = restHighLevelClient.bulk(bulkRequest, MallElasticSearchConfig.COMMON_OPTIONS);
        // 查看你是否含有错误
        boolean b = response.hasFailures();
        List<String> collect = Arrays.stream(response.getItems()).map(item -> {
            return item.getId();
        }).collect(Collectors.toList());
        log.info("商品上架成功：{}",collect);
        return b;
    }
}